--[[
 * Copyright (c) 2010 MoSync AB
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
--]]


maSystemSupportInitialize()

-- DoThenRun
--function RunAll(...)

--end

GDataLoaded = false
Image1 = nil
Image2 = nil

--[[DownloadImage(
	"http://www.mosync.com/sites/all/themes/custom/mosync2/images/phones.png",
	function (image)
		Image1 = image
		Log("Image downloaded")
	end)
--]]

function Main()
	local event = maEventCreate()
	
	DrawBackground()

	while true do
		maWait(0)
		maGetEvent(event)
		if EVENT_TYPE_CLOSE == maEventGetType(event) then
			break
		elseif EVENT_TYPE_POINTER_PRESSED == maEventGetType(event) or
		       EVENT_TYPE_POINTER_DRAGGED == maEventGetType(event) then
			local x = maEventGetX(event)
			local y = maEventGetY(event)
			PaintDot(x, y)
			if GDataLoaded then
				maDrawImage(Image1, x, y)
				maDrawImage(Image2, x + 100, y)
			end
			maUpdateScreen()
		else
			maSystemSupportHandleEvent(event)
		end
	end
	
	maEventDelete(event)
end

function PaintDot(x, y)
	maSetColor(0x2288FF)
	maFillRect(x - 10, y - 20, 20, 20)
end

function DrawBackground()
	maSetColor(0xAAFF00)
	maFillRect(0, 0, GetScreenWidth(), GetScreenHeight())
	maUpdateScreen()
end

function GetScreenWidth()
	return EXTENT_X(maGetScrSize());
end

function GetScreenHeight()
	return EXTENT_Y(maGetScrSize());
end

-- Start the program
-- Main()

function Load()
	local downloadCounter = 2
	
	function CountDown()
		downloadCounter = downloadCounter - 1
		if 0 == downloadCounter then
			GDataLoaded = true
		end
	end
	
	DownloadImage(
		"http://a2.twimg.com/profile_images/392674508/mosyncsquare_normal.png",
		function (image)
			Image1 = image
			CountDown()
		end)

	DownloadImage(
		"http://a2.twimg.com/profile_images/392674508/mosyncsquare_normal.png",
		function (image)
			Image2 = image
			CountDown()
		end)
end

Load()

Main()

